package com.yuexun.dhdoctor.module.mythings.ui;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.base.model.impl.HelpModel;
import com.yuexun.dhdoctor.base.presenter.impl.HelpPresent;
import com.yuexun.dhdoctor.base.ui.IHelpView;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.email.adapter.MailFileAdapter;
import com.yuexun.dhdoctor.module.email.bean.MailFileBean;
import com.yuexun.dhdoctor.module.email.bean.MailFileDataBean;
import com.yuexun.dhdoctor.module.mythings.adapter.FeedbackAdapter;
import com.yuexun.dhdoctor.module.mythings.bean.FeedbackFileBean;
import com.yuexun.dhdoctor.module.mythings.bean.TaskData;
import com.yuexun.dhdoctor.module.mythings.bean.TaskMainBean;
import com.yuexun.dhdoctor.module.mythings.model.impl.ThingDetailModel;
import com.yuexun.dhdoctor.module.mythings.presenter.impl.ThingDetailPresenter;
import com.yuexun.dhdoctor.module.mythings.ui.view.IThingDetailView;
import com.yuexun.dhdoctor.util.URLImageGetter;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;
import com.yuexun.dhdoctor.widget.LoadingDialog;
import com.yuexun.dhdoctor.widget.ModelAddViewNew;

import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/7/27.
 */
public class Act_ThingDetailMyself extends BaseKJActivity implements IThingDetailView, IHelpView {

    @Bind(R.id.thingsdetail_title)
    TextView thingsdetailTitle;
    @Bind(R.id.title_right)
    TextView titleight;
    @Bind(R.id.thingsdetail_from_tv)
    TextView thingsdetailFromTv;
    @Bind(R.id.thingsdetail_date_tv)
    TextView thingsdetailDateTv;
    @Bind(R.id.thingsdetail_content_tv)
    TextView thingsdetailContentTv;
    @Bind(R.id.flv_attachment)
    FixedSwipeListView flvAttachment;
    @Bind(R.id.flv_feedback)
    FixedSwipeListView flvFeedback;
    @Bind(R.id.addmember_sure_btn)
    TextView addmemberSureBtn;
    @Bind(R.id.thingsdetail_bottom_ll)
    RelativeLayout thingsdetailBottomLl;
    @Bind(R.id.ic_seal_done)
    ImageView ic_seal_done;
    @Bind(R.id.ll_extra_file)
    LinearLayout ll_extra_file;
    @Bind(R.id.model_view)
    LinearLayout modelView;

    TaskMainBean taskMainBean = new TaskMainBean();
    //    AttachmentAdapter adapter_attachment;
    MailFileAdapter mailFileAdapter;
    FeedbackAdapter adapter_feedback;

    ArrayList<MailFileDataBean> mailFileDataBeans = new ArrayList<MailFileDataBean>();

    String taskid;
    ThingDetailPresenter presenter;
    HelpPresent helpPresent;
    LoadingDialog dialog;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_thingsdetail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        titleight.setVisibility(View.VISIBLE);
        taskid = getIntent().getExtras().getString("taskid");
        presenter = new ThingDetailPresenter(new ThingDetailModel(), this);
        helpPresent = new HelpPresent(new HelpModel(), this);

        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("taskId", taskid);
        presenter.getTaskDetailDatas(params);

        dialog = new LoadingDialog(aty);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @Override
    @OnClick({R.id.back, R.id.addmember_sure_btn, R.id.title_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.addmember_sure_btn:
                Intent intent = new Intent(this, Act_ThingsFeedback.class);
                intent.putExtra("taskid", taskMainBean.getTaskId());
                aty.startActivityForResult(intent, 1);
                break;
            case R.id.title_right:
                Intent intent2 = new Intent(this, Act_Things_Edit.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("taskMainBean", taskMainBean);
                bundle.putSerializable("filelist", mailFileDataBeans);
                intent2.putExtras(bundle);
                aty.startActivityForResult(intent2, 1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 100:
                taskMainBean.setFeedbackState("2");
                ic_seal_done.setVisibility(View.VISIBLE);
                thingsdetailBottomLl.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    int position;
    MediaPlayer mediaPlayer;
    Thread thread;

    public void refresh(final MediaPlayer mediaPlayer, int position) {
        this.mediaPlayer = mediaPlayer;
        this.position = position;
        if (mediaPlayer != null) {
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    int time = (mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition()) / 1000;
                    if (time > 0) {
                        handler.postDelayed(thread, 1000);
                    } else {
                        try {
                            Thread.sleep(500);  // 延迟1秒
                            thread.interrupt();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    Message msg = handler.obtainMessage();
                    msg.obj = time;
                    msg.what = 1;
                    handler.sendMessage(msg);

                }
            });
            thread.start();
        } else {
            thread.interrupt();
            taskMainBean.getFeedbacks().get(position).setDownTime("");
            adapter_feedback.notifyDataSetChanged();
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    int downTime = (int) msg.obj;
                    taskMainBean.getFeedbacks().get(position).setDownTime(downTime + "");
                    adapter_feedback.notifyDataSetChanged();
                    Log.i("DetaildownTime:", downTime + "");
                    break;

                default:
                    break;
            }

        }

        ;
    };

    @Override
    public void showTaskDetailDatas(TaskData taskData) {
        dialog.dismiss();
        taskMainBean = taskData.getDatas().get(0);


        for (int i = 0; i < taskMainBean.getFeedbacks().size(); i++) {
            if (taskMainBean.getFeedbacks().get(i).getFileUrl().length() > 0 && taskMainBean.getFeedbacks().get(i).getFileName().length() > 0
                    && taskMainBean.getFeedbacks().get(i).getFileSize().length() > 0) {
                String[] fileUrl = taskMainBean.getFeedbacks().get(i).getFileUrl().split(";");
                String[] fileSize = taskMainBean.getFeedbacks().get(i).getFileSize().split(";");
                String[] fileName = taskMainBean.getFeedbacks().get(i).getFileName().split(";");

                ArrayList<FeedbackFileBean> feedbackFileBeans = new ArrayList<>();
                for (int j = 0; j < fileUrl.length; j++) {
                    FeedbackFileBean feedbackFileBean = new FeedbackFileBean();
                    feedbackFileBean.setFileName(fileName[j]);
                    feedbackFileBean.setFileUrl(fileUrl[j]);
                    feedbackFileBean.setFileSize(fileSize[j]);
                    feedbackFileBeans.add(feedbackFileBean);
                }
                taskMainBean.getFeedbacks().get(i).setFeedbackFileBeans(feedbackFileBeans);
            }
            adapter_feedback = new FeedbackAdapter(this, flvAttachment, taskMainBean.getFeedbacks(), R.layout.item_feedback);
            flvFeedback.setAdapter(adapter_feedback);
        }

        ic_seal_done.setVisibility(View.GONE);
        thingsdetailBottomLl.setVisibility(View.GONE);

        thingsdetailTitle.setText(taskData.getDatas().get(0).getTitle());
        thingsdetailFromTv.setText(taskData.getDatas().get(0).getFromName());
        thingsdetailDateTv.setText(taskData.getDatas().get(0).getCreateDate());
        if (taskData.getDatas().get(0).getContent() != null && !taskData.getDatas().get(0).getContent().isEmpty()) {
            thingsdetailContentTv.setVisibility(View.VISIBLE);
            thingsdetailContentTv.setMovementMethod(LinkMovementMethod.getInstance());
            thingsdetailContentTv.setText(Html.fromHtml(taskData.getDatas().get(0).getContent().
                    replace("＜", "<").replace("＞", ">").replace(AppConfig.TEXTVIEW_WEB, AppConfig.TEXTVIEW_WEB_All), new URLImageGetter(thingsdetailContentTv), null));
        } else {
            thingsdetailContentTv.setVisibility(View.GONE);
        }

        if (taskData.getDatas().get(0).getAttachment().size() > 0) {
            ll_extra_file.setVisibility(View.VISIBLE);
            mailFileDataBeans.clear();
            for (int i = 0; i < taskData.getDatas().get(0).getAttachment().size(); i++) {
                Map<String, String> params = new HashMap<>();
                params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
                params.put("fileUuid", taskData.getDatas().get(0).getAttachment().get(i).getAttachmentId());
                helpPresent.getFileData(params);
            }
        } else {
            ll_extra_file.setVisibility(View.GONE);
        }

        if (taskData.getStatus().equals("200")) {
            modelView.removeAllViews();
//            modelView.addView(createTxtView(null, "主题", taskMainBean.getTitle()));
            modelView.addView(new ModelAddViewNew(aty).createTxtView(null, "类型", taskMainBean.getConfigName()));
            modelView.setVisibility(View.VISIBLE);
            if (taskMainBean.getDtlList() != null && taskMainBean.getDtlList().size() > 0 &&
                    !taskMainBean.getDtlList().get(0).getShowType().isEmpty()) {
                for (int i = 0; i < taskMainBean.getDtlList().size(); i++) {
                    modelView.addView(new ModelAddViewNew(aty).createTxtView(taskMainBean.getDtlList().get(i), null, null));
                }
            } else {
                modelView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void getFileData(MailFileBean mailFileBean) {
        if (mailFileBean.getStatus().equals("200")) {
            mailFileDataBeans.add(mailFileBean.getDatas().get(0));
            mailFileAdapter = new MailFileAdapter(this, mailFileDataBeans, false);
            flvAttachment.setAdapter(mailFileAdapter);
        } else {
            Log.e("jx", "文件信息获取失败");
        }
    }

}
